package com.cyan.note.service.manager.impl;

import com.cyan.note.common.ApiResult;
import com.cyan.note.common.PageResult;
import com.cyan.note.common.ResultCode;
import com.cyan.note.dto.manager.service.ServiceQuickDTO;
import com.cyan.note.entity.Service;
import com.cyan.note.mapper.ServiceMapper;
import com.cyan.note.service.manager.ManagerServiceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 店长端-服务管理服务实现类
 * 
 * @author ZhangzhenYu
 * @since 2025-01-15
 */
@org.springframework.stereotype.Service
@Slf4j
public class ManagerServiceServiceImpl implements ManagerServiceService {

    @Autowired
    private ServiceMapper serviceMapper;

    @Override
    public ApiResult<PageResult<Service>> getServiceList(Long shopId, Integer page, Integer size, 
            String keyword, String status, String serviceType, Long categoryId, 
            String sortBy, String sortOrder) {
        
        try {
            // 计算分页
            int offset = (page - 1) * size;

            // 查询数据
            List<Service> services = serviceMapper.selectServicePage(shopId, categoryId, 
                    status, serviceType, offset, size);

            // 查询总数
            int total = serviceMapper.countServices(shopId, categoryId, status, serviceType);

            PageResult<Service> pageResult = PageResult.of(services, total, page, size);
            return ApiResult.success(pageResult);
        } catch (Exception e) {
            log.error("查询服务列表失败", e);
            return ApiResult.error(ResultCode.ERROR, "查询服务列表失败");
        }
    }

    @Override
    public ApiResult<Service> getServiceDetail(Long shopId, Long serviceId) {
        try {
            Service service = serviceMapper.selectById(serviceId);
            if (service == null || !service.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }
            return ApiResult.success(service);
        } catch (Exception e) {
            log.error("查询服务详情失败", e);
            return ApiResult.error(ResultCode.ERROR, "查询服务详情失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> createService(Service service, Long operatorId) {
        try {
            // 检查服务编号是否存在
            Integer count = serviceMapper.countByServiceCode(service.getShopId(), 
                    service.getServiceCode(), null);
            if (count > 0) {
                return ApiResult.error(ResultCode.DUPLICATE_RESOURCE, "服务编号已存在");
            }

            // 设置默认值
            service.setStatus(Service.Status.DRAFT);
            service.setIsRecommended(false);
            service.setIsHot(false);
            service.setViewCount(0);
            service.setOrderCount(0);
            service.setRatingCount(0);
            service.setCreatedAt(LocalDateTime.now());
            service.setUpdatedAt(LocalDateTime.now());

            int result = serviceMapper.insert(service);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "新增服务失败");
            }
        } catch (Exception e) {
            log.error("新增服务失败", e);
            return ApiResult.error(ResultCode.ERROR, "新增服务失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> updateService(Service service, Long operatorId) {
        try {
            // 检查服务是否存在
            Service existingService = serviceMapper.selectById(service.getId());
            if (existingService == null || !existingService.getShopId().equals(service.getShopId())) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }

            // 检查服务编号冲突
            Integer count = serviceMapper.countByServiceCode(service.getShopId(), 
                    service.getServiceCode(), service.getId());
            if (count > 0) {
                return ApiResult.error(ResultCode.DUPLICATE_RESOURCE, "服务编号已存在");
            }

            service.setUpdatedAt(LocalDateTime.now());
            int result = serviceMapper.updateById(service);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "更新服务失败");
            }
        } catch (Exception e) {
            log.error("更新服务失败", e);
            return ApiResult.error(ResultCode.ERROR, "更新服务失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> deleteService(Long shopId, Long serviceId, Long operatorId) {
        try {
            // 检查服务是否存在
            Service service = serviceMapper.selectById(serviceId);
            if (service == null || !service.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }

            int result = serviceMapper.deleteById(serviceId);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "删除服务失败");
            }
        } catch (Exception e) {
            log.error("删除服务失败", e);
            return ApiResult.error(ResultCode.ERROR, "删除服务失败");
        }
    }

    @Override
    public ApiResult<List<ServiceQuickDTO>> getQuickServices(Long shopId) {
        try {
            List<Service> services = serviceMapper.selectActiveServices(shopId);
            
            List<ServiceQuickDTO> result = new ArrayList<>();
            for (Service service : services) {
                ServiceQuickDTO dto = new ServiceQuickDTO();
                dto.setId(service.getId());
                dto.setServiceName(service.getServiceName());
                dto.setServiceType(service.getServiceType());
                dto.setBasePrice(service.getBasePrice());
                dto.setMinDuration(service.getMinDuration());
                dto.setMaxDuration(service.getMaxDuration());
                result.add(dto);
            }

            return ApiResult.success(result);
        } catch (Exception e) {
            log.error("查询快速服务列表失败", e);
            return ApiResult.error(ResultCode.ERROR, "查询快速服务列表失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> updateServiceStatus(Long shopId, Long serviceId, String status, Long operatorId) {
        try {
            Service service = serviceMapper.selectById(serviceId);
            if (service == null || !service.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }

            service.setStatus(status);
            service.setUpdatedAt(LocalDateTime.now());
            
            int result = serviceMapper.updateById(service);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "更新服务状态失败");
            }
        } catch (Exception e) {
            log.error("更新服务状态失败", e);
            return ApiResult.error(ResultCode.ERROR, "更新服务状态失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> copyService(Long shopId, Long serviceId, Long operatorId) {
        try {
            Service original = serviceMapper.selectById(serviceId);
            if (original == null || !original.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "服务不存在");
            }

            // 创建副本
            Service copy = new Service();
            copy.setShopId(original.getShopId());
            copy.setServiceCode(original.getServiceCode() + "_copy_" + System.currentTimeMillis());
            copy.setServiceName(original.getServiceName() + " (副本)");
            copy.setServiceDescription(original.getServiceDescription());
            copy.setCategoryId(original.getCategoryId());
            copy.setServiceType(original.getServiceType());
            copy.setBasePrice(original.getBasePrice());
            copy.setMinDuration(original.getMinDuration());
            copy.setMaxDuration(original.getMaxDuration());
            copy.setCoverImage(original.getCoverImage());
            copy.setImages(original.getImages());
            copy.setTags(original.getTags());
            copy.setRequirements(original.getRequirements());
            copy.setFeatures(original.getFeatures());
            copy.setStatus(Service.Status.DRAFT);
            copy.setDisplayOrder(original.getDisplayOrder());
            copy.setIsRecommended(false);
            copy.setIsHot(false);
            copy.setViewCount(0);
            copy.setOrderCount(0);
            copy.setRatingCount(0);
            copy.setCreatedBy(operatorId);
            copy.setCreatedAt(LocalDateTime.now());
            copy.setUpdatedAt(LocalDateTime.now());

            int result = serviceMapper.insert(copy);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "复制服务失败");
            }
        } catch (Exception e) {
            log.error("复制服务失败", e);
            return ApiResult.error(ResultCode.ERROR, "复制服务失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> batchUpdateSort(Long shopId, List<Long> serviceIds, Long operatorId) {
        try {
            for (int i = 0; i < serviceIds.size(); i++) {
                Long serviceId = serviceIds.get(i);
                Service service = serviceMapper.selectById(serviceId);
                if (service != null && service.getShopId().equals(shopId)) {
                    service.setDisplayOrder(i + 1);
                    service.setUpdatedAt(LocalDateTime.now());
                    serviceMapper.updateById(service);
                }
            }
            return ApiResult.success();
        } catch (Exception e) {
            log.error("批量更新排序失败", e);
            return ApiResult.error(ResultCode.ERROR, "批量更新排序失败");
        }
    }
}